
	function supportstorage() {
		if (typeof window.localStorage == 'object')
			return true;
		else
			return false;
	}
	function handleSaveLayout() {
		var e = $(".demo").html();
		if (!stopsave && e != window.demoHtml) {
			stopsave++;
			window.demoHtml = e;
			saveLayout();
			stopsave--;
		}
	}
var layouthistory;
//保存当前的布局
	function saveLayout() {
		var data = layouthistory;
		if (!data) {
			data = {};
			data.count = 0;
			data.list = [];
		
		}
		if (data.list.length > data.count) {
			for (i = data.count; i < data.list.length; i++)
				data.list[i] = null;
		}
		data.list[data.count] = window.demoHtml;
		data.count++;
		data.Id = $("#PageId").val();
		data.Title = $("#pageTitle").val();
		if (supportstorage()) {
			localStorage.setItem("layoutdata", JSON.stringify(data));
		}
		layouthistory = data;
		 
	}
	function downloadLayout() {

		$.ajax({
			type: "POST",
			url: "/build/downloadLayout",
			data: { layout: $('#download-layout').html() },
			success: function (data) { window.location.href = '/build/download'; }
		});
	}
	function downloadHtmlLayout() {
		$.ajax({
			type: "POST",
			url: "/build/downloadLayout",
			data: { layout: $('#download-layout').html() },
			success: function (data) { window.location.href = '/build/downloadHtml'; }
		});
	}
	function undoLayout() {
		var data = layouthistory;
		//console.log(data);
		if (data) {
			if (data.count < 2) return false;
			window.demoHtml = data.list[data.count - 2];
			data.count--;
			$('.demo').html(window.demoHtml);
			if (supportstorage()) {
				localStorage.setItem("layoutdata", JSON.stringify(data));
			}
			return true;
		}
		return false;
		/*$.ajax({  
			type: "POST",  
			url: "/build/getPreviousLayout",  
			data: { },  
			success: function(data) {
				undoOperation(data);
			}
		});*/
	}
	function redoLayout() {
		var data = layouthistory;
		if (data) {
			if (data.list[data.count]) {
				window.demoHtml = data.list[data.count];
				data.count++;
				$('.demo').html(window.demoHtml);
				if (supportstorage()) {
					localStorage.setItem("layoutdata", JSON.stringify(data));
				}
				return true;
			}
		}
		return false;

	}
	function handleJsIds() {
		handleModalIds();
		handleAccordionIds();
		handleCarouselIds();
		handleTabsIds()
}
  
	function handleAccordionIds() {
		var e = $(".demo #myAccordion");
		var t = randomNumber();
		var n = "accordion-" + t;
		var r;
		e.attr("id", n);
		e.find(".accordion-group").each(function (e, t) {
			r = "accordion-element-" + randomNumber();
			$(t).find(".accordion-toggle").each(function (e, t) {
				$(t).attr("data-parent", "#" + n);
				$(t).attr("href", "#" + r)
			});
			$(t).find(".accordion-body").each(function (e, t) {
				$(t).attr("id", r)
			})
		})
	}
	function handleCarouselIds() {
		var e = $(".demo #myCarousel");
		var t = randomNumber();
		var n = "carousel-" + t;
		e.attr("id", n);
		e.find(".carousel-indicators li").each(function (e, t) {
			$(t).attr("data-target", "#" + n)
		});
		e.find(".left").attr("href", "#" + n);
		e.find(".right").attr("href", "#" + n)
	}
	function handleModalIds() {
		var e = $(".demo #myModalLink");
		var t = randomNumber();
		var n = "modal-container-" + t;
		var r = "modal-" + t;
		e.attr("id", r);
		e.attr("href", "#" + n);
		e.next().attr("id", n)
	}
	function handleTabsIds() {
		var e = $(".demo #myTabs");
		var t = randomNumber();
		var n = "tabs-" + t;
		e.attr("id", n);
		e.find(".tab-pane").each(function (e, t) {
			var n = $(t).attr("id");
			var r = "panel-" + randomNumber();
			$(t).attr("id", r);
			$(t).parent().parent().find("a[href=#" + n + "]").attr("href", "#" + r)
		})
	}
	function randomNumber() {
		return randomFromInterval(1, 1e6)
	}
	function randomFromInterval(e, t) {
		return Math.floor(Math.random() * (t - e + 1) + e)
	}
	function gridSystemGenerator() {
		$(".lyrow .preview input").bind("keyup", function () {
			var e = 0;
			var t = "";
			var n = $(this).val().split(" ", 12);
			$.each(n, function (n, r) {
				e = e + parseInt(r);
				t += '<div class="col-lg-' + r + ' column"></div>'
			});
			if (e == 12) {
				$(this).parent().next().children().html(t);
				$(this).parent().prev().show()
			} else {
				$(this).parent().prev().hide()
			}
		})
	}
	function configurationElm(e, t) {
		$(".demo").delegate(".configuration > a", "click", function (e) {
			e.preventDefault();
			var t = $(this).parent().next().next().children();
			$(this).toggleClass("active");
			t.toggleClass($(this).attr("rel"))
		});
		$(".demo").delegate(".configuration .dropdown-menu a", "click", function (e) {
			e.preventDefault();
			var t = $(this).parent().parent();
			var n = t.parent().parent().next().next().children();
			t.find("li").removeClass("active");
			$(this).parent().addClass("active");
			var r = "";
			t.find("a").each(function () {
				r += $(this).attr("rel") + " "
			});
			t.parent().removeClass("open");
			n.removeClass(r);
			n.addClass($(this).attr("rel"))
		})
	}
	function removeElm() {
		$(".demo").delegate(".remove", "click", function (e) {
			e.preventDefault();
			$(this).parent().remove();
			if (!$(".demo .lyrow").length > 0) {
				clearDemo()
			}
		})
	}
	function clearDemo() {
		$(".demo").empty();
		layouthistory = null;
		if (supportstorage())
			localStorage.removeItem("layoutdata");
	}
	function removeMenuClasses() {
		$("#menu-layoutit li button").removeClass("active")
	}
	function changeStructure(e, t) {
		$("#download-layout ." + e).removeClass(e).addClass(t)
	}
	function cleanHtml(e) {
		$(e).parent().append($(e).children().html())
	}
	function downloadLayoutSrc() {
		var e = "";
		$("#download-layout").children().html($(".demo").html());
		var t = $("#download-layout").children();
		t.find(".preview, .configuration, .drag, .remove").remove();
		t.find(".lyrow").addClass("removeClean");
		t.find(".box-element").addClass("removeClean");
		t.find(".lyrow .lyrow .lyrow .lyrow .lyrow .removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".lyrow .lyrow .lyrow .lyrow .removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".lyrow .lyrow .lyrow .removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".lyrow .lyrow .removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".lyrow .removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".removeClean").each(function () {
			cleanHtml(this)
		});
		t.find(".removeClean").remove();
		$("#download-layout .column").removeClass("ui-sortable");
		$("#download-layout .row-fluid").removeClass("clearfix").children().removeClass("column");
		if ($("#download-layout .container").length > 0) {
			changeStructure("row-fluid", "row")
		}
		formatSrc = $.htmlClean($("#download-layout").html(), {
			format: true,
			allowedAttributes: [
				["id"],
				["class"],
				["data-toggle"],
				["data-target"],
				["data-parent"],
				["role"],
				["data-dismiss"],
				["aria-labelledby"],
				["aria-hidden"],
				["data-slide-to"],
				["data-slide"]
			]
		});
		$("#download-layout").html(formatSrc);
		$("#downloadModal textarea").empty();
		$("#downloadModal textarea").val(formatSrc);
		return formatSrc;
	}
	var currentDocument = null;
	var timerSave = 1000;
	var stopsave = 0;
	var startdrag = 0;
	var demoHtml = $(".demo").html();
	var currenteditor = null;
	$(window).resize(function () {
		$("body").css("min-height", $(window).height() - 90);
		$(".demo").css("min-height", $(window).height() - 160)
	});
function restoreData() {
	if (supportstorage()) {
		var ldata = localStorage.getItem("layoutdata");

		if (ldata == undefined || ldata == null || ldata.length == 0) {
			window.demoHtml = "";
			clearDemo();
		}
		else {
			if (!layouthistory) return false;
			layouthistory = JSON.parse(ldata);
			window.demoHtml = layouthistory.list[layouthistory.count - 1];
		}
		if (window.demoHtml) $(".demo").html(window.demoHtml);

		$("#PageId").val(ldata.Id);
		$("#pageTitle").val(ldata.Title);

	}
}
function restoreDataFromHtml(html) {
	if (html == "") {
		layouthistory = {};
		layouthistory.count = 0;
		layouthistory.list = [];
		window.demoHtml = "";
		clearDemo();
	}
	else {


		var ldata = JSON.parse(html);
		
		if (ldata == undefined || ldata == null || ldata.length == 0) {
			window.demoHtml = "";
			clearDemo();
		}
		else {
			layouthistory = {};
			layouthistory.count = 1;
			layouthistory.list = [];
			layouthistory.list.push(ldata);
			window.demoHtml = layouthistory.list[layouthistory.count - 1];
			if (window.demoHtml) $(".demo").html(window.demoHtml);
		}
	}
	
 
}
function SetContentEdit() {
	CKEDITOR.disableAutoInline = true;

	var contenthandle = CKEDITOR.replace('contenteditor', {
		language: 'zh-cn',
		contentsCss: ['/Content/css/bootstrap.min.css'],
		allowedContent: true
	});
}
function restoreFromDbData(html) {
	if (html == null || html == "")
		html = "";
 
	restoreDataFromHtml(html);
	saveLayout();
}
function saveLayoutToDb() {
	var data = layouthistory;
	if (!data) {
		data = {};
		data.count = 0;
		data.list = [];
	}
	if (data.list.length > data.count) {
		for (i = data.count; i < data.list.length; i++)
			data.list[i] = null;
	}
	data.list[data.count] = window.demoHtml;
	data.count++;

	layouthistory = data;
	var html=downloadLayoutSrc();//获取清理后端de html
	$.post("/Scada/ScaddDesigner/SavePage", { "Id": $("#PageId").val(), "LayoutData": JSON.stringify(data.list[data.count - 1]), "html": html }, function (result) {
		if (result.code == 0) {
			WebDesigner.showMessage("保存页面成功");
			saveLayout();//保存到缓存
		}
		else {
			WebDesigner.showMessage("保存页面失败");
		}

	});

}
	function initContainer() {
		$(".demo, .demo .column").sortable({
			connectWith: ".column",
			opacity: .35,
			handle: ".drag",
			start: function (e, t) {
				if (!startdrag) stopsave++;
				startdrag = 1;
			},
			stop: function (e, t) {
				if (stopsave > 0) stopsave--;
				startdrag = 0;
				
			}
		});
		configurationElm();
		//加载页面
		WebDesigner.InitDesigner();
	
}
function documentready() {
	
	$(document).ready(function () {
		CKEDITOR.disableAutoInline = true;
		restoreData();
		var contenthandle = CKEDITOR.replace('contenteditor', {
			language: 'zh-cn',
			contentsCss: ['/Content/css/bootstrap.min.css'],
			allowedContent: true
		});
		$("body").css("min-height", $(window).height() - 90);
		$(".demo").css("min-height", $(window).height() - 160);
		$(".lyrow").draggable({
			connectToSortable: ".demo",
			helper: "clone",
			handle: ".drag",
			start: function (e, t) {
				if (!startdrag) stopsave++;
				startdrag = 1;
			},
			drag: function (e, t) {
				t.helper.width(400)
			},
			stop: function (e, t) {
				$(".demo .column").sortable({
					opacity: .35,
					connectWith: ".column",
					start: function (e, t) {
						if (!startdrag) stopsave++;
						startdrag = 1;
					},
					stop: function (e, t) {
						if (stopsave > 0) stopsave--;
						startdrag = 0;
					}
				});
				if (stopsave > 0) stopsave--;
				startdrag = 0;
				initContainer();
			}
		});
		$(".box").draggable({
			connectToSortable: ".column",
			helper: "clone",
			handle: ".drag",
			start: function (e, t) {
				if (!startdrag) stopsave++;
				startdrag = 1;
			},
			drag: function (e, t) {
				t.helper.width(400)
			},
			stop: function () {
				handleJsIds();
				if (stopsave > 0) stopsave--;
				startdrag = 0;
				initContainer();
			}
		});

		$('body.edit .demo').on("click", "[data-target='#editorModal']", function (e) {
			e.preventDefault();
			currenteditor = $(this).parent().parent().find('.view');
			var eText = currenteditor.html();
			contenthandle.setData(eText);
		});
		initContainer();
		$("#savecontent").click(function (e) {
			e.preventDefault();
			currenteditor.html(contenthandle.getData());
		});
		$("[data-target='#downloadModal']").click(function (e) {
			e.preventDefault();
			downloadLayoutSrc();
		});
		$("[data-target='#shareModal']").click(function (e) {
			e.preventDefault();
			handleSaveLayout();
		});
		$("#download").click(function () {
			downloadLayout();
			return false
		});
		$("#downloadhtml").click(function () {
			downloadHtmlLayout();
			return false
		});
		$("#edit").click(function () {
			$("body").removeClass("devpreview sourcepreview");
			$("body").addClass("edit");
			removeMenuClasses();
			$(this).addClass("active");
			return false
		});
		$("#clear").click(function (e) {
			e.preventDefault();
			clearDemo();
		});
		$("#devpreview").click(function () {
			$("body").removeClass("edit sourcepreview");
			$("body").addClass("devpreview");
			removeMenuClasses();
			$(this).addClass("active");
			return false
		});
		$("#sourcepreview").click(function () {
			$("body").removeClass("edit");
			$("body").addClass("devpreview sourcepreview");
			removeMenuClasses();
			$(this).addClass("active");
			return false
		});
		$("#fluidPage").click(function (e) {
			e.preventDefault();
			changeStructure("container", "container-fluid");
			$("#fixedPage").removeClass("active");
			$(this).addClass("active");
			downloadLayoutSrc()
		});
		$("#fixedPage").click(function (e) {
			e.preventDefault();
			changeStructure("container-fluid", "container");
			$("#fluidPage").removeClass("active");
			$(this).addClass("active");
			downloadLayoutSrc()
		});
		$(".nav-header").click(function () {
			$(".sidebar-nav .boxes, .sidebar-nav .rows").hide();
			$(this).next().slideDown()
		});
		$('#undo').click(function () {
			stopsave++;
			if (undoLayout()) initContainer();
			stopsave--;
		});
		$('#redo').click(function () {
			stopsave++;
			if (redoLayout()) initContainer();
			stopsave--;
		});
		removeElm();
		gridSystemGenerator();
		setInterval(function () {
			handleSaveLayout()
		}, timerSave)
	})
}
 

documentready();
function SCADA_WebDesigner() {
	//定义一个加载页面的方法
	this.LoadPages = function () {
		//加载通道类型
		$.get("/Scada/ScaddDesigner/GetPages", null, function (result) {
			$("#mypage").empty();
			$("#mypage").append("<option value=''>请选择一个页面</option>");
			for (var i = 0; i < result.data.length; i++) {
			
				$("#mypage").append("<option value='" + result.data[i].Id + "'>" + result.data[i].PageTitle + "</option>");
			}
 
		});
	}
	this.InitDesigner = function () {
		$("#PageId").val("0");
		WebDesigner.LoadPages();
		$("#btload").click(function (e) {

			if ($("#mypage").val() == "") {
				WebDesigner.showMessage("请选择要加载的页面");
			}
			else {
				$("#LoadPage").modal('hide');
				//加载一个页面HTML
				var id = $("#mypage").val();
				$("#PageId").val(id);
				$.get("/Scada/ScaddDesigner/GetPage", { "id": id }, function (result) {
					var html = result.LayoutData;
					$("#pageTitle").html("当前加载页面标题：" + result.PageTitle);
					$("#jsFile").val(result.JsContent);
					$("#PageUid").val(result.PageUid);
					restoreFromDbData(html);
					initContainer();

				});
			}

		});

		$("#pagepreview").click(function (e) {

			var uid = $("#PageUid").val();
			window.open("../WebTemplate/" + uid+".htm");

		});
		
		$("#btSaveJs").click(function (e) {
	 
			var id = $("#PageId").val();
			$.post("/Scada/ScaddDesigner/SaveJsContent", { "Id": id, "JsContent": $("#jsFile").val() }, function (result) {

				if (result.code == 0) {
					WebDesigner.showMessage("保存脚本成功");
				}
				else {
					WebDesigner.showMessage("保存脚本失败");
                }
			});

		});
		
		$("#btPageNew").click(function (e) {

			if ($("#tbPageTitle").val() == "") {
				WebDesigner.showMessage("请输入页面标题");
			}
			else {
				$.post("/Scada/ScaddDesigner/AddPage", { "title": $("#tbPageTitle").val(), "remark": $("#tbPageRemark").val() }, function (result) {
					if (result.code == 0) {
						$("#newPage").modal('hide');
						$("#PageId").val(result.data.Id);
						$("#pageTitle").html("当前加载页面标题：" + result.data.PageTitle);
						$("#jsFile").val(result.data.JsContent);
						$("#PageUid").val(result.data.PageUid);
						
						restoreFromDbData("");
					
						WebDesigner.LoadPages();
					}
					else {
						WebDesigner.showMessage("新建页面异常");
					}

				});
			}
		});
		$("#save").click(function (e) {
			if ($("#PageId").val() != "" && $("#PageId").val() != 0) {
				saveLayoutToDb();
			}
		});


	}
	this.showMessage = function (msg)
	{
		$("#mesgContain").html(msg);
		$("#MessageBox").modal('show');
		
	}
}
var WebDesigner = new SCADA_WebDesigner();
 